import { getToken, setToken } from './token.js';

// 基础请求URL
const BASE_URL = 'https://www.bowenfuwu.cn';

// 请求拦截器
const requestInterceptor = (config) => {
  const token = getToken();
  if (token) {
    config.header = {
      ...config.header,
      'Authorization': `Bearer ${token}`
    };
  }
  return config;
};

// 响应拦截器
const responseInterceptor = (response) => {
  // 处理业务层面的错误（状态码200但返回error）
  if (response.data && response.data.error) {
    let errorMsg = response.data.error;
    uni.showToast({
      title: errorMsg,
      icon: 'none'
    });
    return Promise.reject(new Error(errorMsg));
  }

  // 处理HTTP状态码
  if (response.statusCode !== 200) {
    let errorMsg = '请求失败';
    switch (response.statusCode) {
      case 401:
        errorMsg = '请重新登录';
        break;
      case 403:
        errorMsg = '暂无权限访问';
        break;
      case 404:
        errorMsg = '请求的资源不存在';
        break;
      case 500:
        errorMsg = '服务器内部错误';
        break;
      default:
        errorMsg = `请求失败(${response.statusCode})`;
    }
    uni.showToast({
      title: errorMsg,
      icon: 'none'
    });
    return Promise.reject(new Error(errorMsg));
  }

  return response.data;
};

// 请求方法封装
const request = (options) => {
  // 合并基础URL
  options.url = `${BASE_URL}${options.url}`;
  
  // 应用请求拦截器
  options = requestInterceptor(options);
  
  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      success: (res) => {
        try {
          const result = responseInterceptor(res);
          resolve(result);
        } catch (error) {
          reject(error);
        }
      },
      fail: (err) => {
        const errorMsg = '网络错误，请重试';
        uni.showToast({
          title: errorMsg,
          icon: 'none'
        });
        reject(errorMsg);
      }
    });
  });
};

export default request;